Encode a Lua value to JSON string (json.encode)
Declaration
jsonText, err = json.encode(value)
Parameters
- value
Table or String or Number or Boolean or json.null. The Lua value to convert to JSON text.
Returns
- jsonText
String or nil. JSON string on success; nil on failure. - err
String or nil. Error message when conversion fails (i.e., when jsonText is nil).
Description
Converting Lua values to JSON makes it easy to interoperate with other languages.
Note: not every Lua value can be encoded to JSON, e.g., userdata, functions, or tables containing them.
This function can be used in XUI.
Example
local tb = {
["name"] = "alice",
["message"] = "hello, world",
scores = {
90, 85, 72, 100, 68,
},
nullvalue = json.null,
}
local jsonstr = json.encode(tb)
sys.alert(jsonstr)
--
local tmp = json.decode(jsonstr)
sys.alert(tmp.scores[4])
sys.alert(tostring(tmp.nullvalue))
Note: Uses sys.alert